<template>
  <div class="form-widget-container">
    <el-form
      class="full-height-width widget-form"
      :label-position="labelPosition"
      :inline-message="true"
      :class="[customClass, layoutType + '-layout']"
      :size="size"
      :validate-on-rule-change="false"
      :style="{ 'width': formWidth, 'margin': '0 auto' }"
    >

      <template v-if="designer.widgetList.length === 0">
        <div class="no-widget-hint">{{i18nt('designer.noWidgetHint')}}</div>
      </template>

      <div class="form-widget-canvas" id="formWidgetCanvas">
        <draggable :list="designer.widgetList" item-key="id" v-bind="{group:'dragGroup', ghostClass: 'ghost',animation: 400}"
                   tag="div" :component-data="{name: 'fade', class: 'canvas-drag-drop-zone'}"
                   handle=".drag-handler" @end="onDragEnd" @add="onDragAdd" @update="onDragUpdate" :move="checkMove">
          <template #item="{ element: widget, index }">
            <div class="form-widget-list"  :style="{ 'height': !!widget.options.cellHeight ? widget.options.cellHeight : '' }">
              <template v-if="'container' === widget.category">
                <component :is="getWidgetName(widget)" :widget="widget" :designer="designer" :key="widget.id" :parent-list="designer.widgetList"
                                  :index-of-parent-list="index" :parent-widget="null"></component>
              </template>
              <template v-else>
                <component :is="getWidgetName(widget)" :field="widget" :designer="designer" :key="widget.id" :parent-list="designer.widgetList"
                              :index-of-parent-list="index" :parent-widget="null" :design-state="true"></component>
              </template>
            </div>
          </template>
        </draggable>
      </div>

    </el-form>

  </div>
</template>

<script>
  import '@/components/form-designer/form-widget/container-widget/index'
  import FieldComponents from '@/components/form-designer/form-widget/field-widget/index'
  import i18n from "@/utils/i18n"
  import { deepClone, getSubFormNameByFieldId } from "@/utils/util"
  import eventBus from "@/utils/event-bus"

  export default {
    name: "VFormWidget",
    componentName: "VFormWidget",
    mixins: [i18n],
    components: {
      ...FieldComponents,
    },
    props: {
      designer: Object,
      formConfig: Object,
      optionData: { //prop传入的选项数据
        type: Object,
        default: () => ({})
      },
      globalDsv: {
        type: Object,
        default: () => ({})
      },
    },
    provide() {
      return {
        refList: this.widgetRefList,
        getFormConfig: () => this.formConfig,  /* 解决provide传递formConfig属性的响应式更新问题！！ */
        getGlobalDsv: () => this.globalDsv, // 全局数据源变量
        globalOptionData: this.optionData,
        getOptionData: () => this.optionData,
        getReadMode: () => false,
        globalModel: {
          formModel: this.formModel,
        },
        getSubFormFieldFlag: () => false,
        getSubFormName: () => '',
        getObjectFieldFlag: () => false,  //是否对象容器字段
        getObjectName: () => '',  //返回对象容器的名称
        getDSResultCache: () => this.dsResultCache,
        isMixMode: () => false,
        responsiveLayoutIsDisabled: () => false,
        setCETriggerFlag: () => {},
        clearCETriggerFlag: () => {},
        getCEOCDisabledFlag: () => false,
      }
    },
    inject: ['getDesignerConfig'],
    data() {
      return {
        formModel: {},
        widgetRefList: {}, // 存放当前widget组件防止重名
        dsResultCache: {},
      }
    },
    computed: {
      labelPosition() {
        if (!!this.formConfig && (this.formConfig.layoutType === 'H5') && this.formConfig.h5LabelTop) {
          return 'top'
        }

        if (!!this.designer.formConfig && !!this.designer.formConfig.labelPosition) {
          return this.designer.formConfig.labelPosition
        }

        return 'left'
      },

      size() {
        if (!!this.designer.formConfig && !!this.designer.formConfig.size) {
          return this.designer.formConfig.size
        }

        return 'default'
      },

      customClass() {
        return this.designer.formConfig.customClass || ''
      },

      layoutType() {
        return this.designer.getLayoutType()
      },
      
      formWidth() {
        if (this.designer.formConfig && this.designer.formConfig.formWidth) {
          return this.designer.formConfig.formWidth + (this.designer.formConfig.formWidthUnit || '%');
        } else {
          return '100%';
        }
      }
    },
    watch: {
      'designer.widgetList': {
        deep: true,
        handler(val) {
          //
        }
      },

      'designer.formConfig': {
        deep: true,
        handler(val) {
          //
        }
      },

    },
    created() {
      //this.designer.initDesigner( !!this.getDesignerConfig().resetFormJson )  //此行代码已移动到form-designer，以便提前赋值formConfig！！
      this.designer.loadPresetCssCode( this.getDesignerConfig().presetCssCode )
    },
    mounted() {
      this.disableFirefoxDefaultDrop()  /* 禁用Firefox默认拖拽搜索功能!! */
      this.designer.registerFormWidget(this)
    },
    methods: {
      getWidgetName(widget) {
        return widget.type + '-widget'
      },

      disableFirefoxDefaultDrop() {
        let isFirefox = (navigator.userAgent.toLowerCase().indexOf("firefox") !== -1)
        if (isFirefox) {
          document.body.ondrop = function (event) {
            event.stopPropagation();
            event.preventDefault();
          }
        }
      },

      onDragEnd(evt) {
        // console.log('drag end000', evt)
      },

      onDragAdd(evt) {
        console.log('中间区域 onAdd', evt)
        const newIndex = evt.newIndex
        if (!!this.designer.widgetList[newIndex]) {
          const item = deepClone(this.designer.widgetList[newIndex]);
          // const item = this.designer.widgetList[newIndex];
          console.log('中间区域 onAdd item', item)
          eventBus.$emit('widget__list__dataDomain', item)
          this.designer.setSelected( this.designer.widgetList[newIndex] )
        }

        this.designer.emitHistoryChange()
        this.designer.emitEvent('field-selected', null)
      },

      onDragUpdate() {  /* 在VueDraggable内拖拽组件发生位置变化时会触发update，未发生组件位置变化不会触发！！ */
        this.designer.emitHistoryChange()
      },

      checkMove(evt) {
        return this.designer.checkWidgetMove(evt)
      },

      getFormData() {
        return this.formModel
      },

      getWidgetRef(widgetName, showError = false) {
        let foundRef = this.widgetRefList[widgetName]
        if (!foundRef) {
          console.error('重要提示：', '表单设计器的getWidgetRef方法已不支持获取子表单内部组件，请使用getWidgetRefById方法！')

          if (showError) {
            this.$message.error(this.i18nt('designer.hint.refNotFound') + widgetName)
          }
        }
        return foundRef
      },

      getSelectedWidgetRef() {
        const widgetName = this.designer.selectedWidgetName
        const widgetId = this.designer.selectedId
        return this.getWidgetRefById(widgetId, widgetName)

      },

      /**
       * 获取子表单内部组件
       * @param widgetId 
       * @param widgetName 
       */
      getWidgetRefById(widgetId, widgetName) {
        const sfName = getSubFormNameByFieldId(this.designer.widgetList, widgetId);
        if (!!sfName) {
          return this.widgetRefList[widgetName + '@sf' + sfName]
        } else {
          return this.widgetRefList[widgetName]
        }
      },

      clearWidgetRefList() {
        Object.keys(this.widgetRefList).forEach(key => {
          delete this.widgetRefList[key]
        })
      },

      deleteWidgetRef(widgetRefName, subFormName) {
        if (!subFormName) {
          delete this.widgetRefList[widgetRefName]
        } else {
          delete this.widgetRefList[widgetRefName + '@sf' + subFormName]
        }
      },

      /* 删除容器组件的所有内嵌组件ref */
      deleteChildrenRef(childrenRefNames) {
        childrenRefNames.forEach((childRefName) => {
          delete this.widgetRefList[childRefName]
        })
      },

    }
  }
</script>

<style lang="scss" scoped>
  .container-scroll-bar {
    :deep(.el-scrollbar__wrap), :deep(.el-scrollbar__view) {
      overflow-x: hidden;
    }
  }

  .form-widget-container {
    padding: 10px;
    background: #f1f2f3;

    overflow-x: hidden;
    overflow-y: auto;

    .el-form.full-height-width {
      height: 100%;
      padding: 3px;
      background: #ffffff;

      .no-widget-hint {
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        text-align: center;
        font-size: 18px;
        color: #999999;
      }

      .form-widget-canvas {
        padding: 3px;

        div.canvas-drag-drop-zone {
          height: 100%;
        }
      }

      .canvas-drag-drop-zone > .form-widget-list {
        //display: inline;  /* 开启这行css会导致画布上的组件很难拖入栅格容器，不开启则会导致按钮组件的行内显示属性在设计状态不生效！ */
      }
    }

    /* 隐藏组件拖拽状态中显示的黑点 */
    :deep(li.container-widget-item), :deep(li.field-widget-item) {
      list-style: none;
    }

    .el-form.PC-layout {
      //
    }

    .el-form.Pad-layout {
      margin: 0 auto;
      max-width: 960px;
      border-radius: 15px;
      box-shadow: 0 0 1px 10px #495060;
    }

    .el-form.H5-layout {
      margin: 0 auto;
      width: 420px;
      border-radius: 15px;
      //border-width: 10px;
      box-shadow: 0 0 1px 10px #495060;
    }

    .el-form.widget-form :deep(.el-row) {
      padding: 2px;
      border: 1px dashed rgba(170, 170, 170, 0.75);
    }
  }

  .grid-cell {
    min-height: 30px;
    border-right: 1px dotted #cccccc;

  }

  .fade-enter-active, .fade-leave-active {
    transition: opacity .5s;
  }

  .fade-enter, .fade-leave-to {
    opacity: 0;
  }
</style>
<style lang="scss">
.widget-form.el-form--label-top .el-form-item__label {
  height: 26px !important;
  margin-top: 8px;
  margin-bottom: 2px !important;
}

.widget-form .field-wrapper.form-textarea-label .el-form-item {
  align-items: flex-start;
}

</style>